<script lang="ts" setup>
import useLoading from '@/hooks/useLoading';
import HomeRequest from '@/request/homeRequest';
import { useAppStore } from '@/store';
import { isObject } from '@/utils/is';
import Location from '@/utils/location';
import { navigate } from '@/utils/navigate';
import to from '@/utils/to';
import zPaging from 'z-paging/components/z-paging/z-paging.vue';

interface IState {
  selectTag: number[];
  newList: IObtainNewsListRes[];
  params: {
    beeperId: number;
    pageNo: number;
    pageSize: number;
    libraryName?: string;
    cityName?: string;
    provinceName?: string;
    areaName?: string;
    tagIds?: string;
    secondClassifyIds: string;
  };
  tagList: { id: number; name: string }[];
}

const { showLoading, hideLoading } = useLoading();
const store = useAppStore();
const { btnInformation, beeperId } = store.$state;
const state = reactive<IState>({ selectTag: [], newList: [], params: { beeperId, secondClassifyIds: btnInformation!.classifyIds, pageNo: 1, pageSize: 10 }, tagList: [] });
const pagingRef = ref<InstanceType<typeof zPaging> | null>(null);

onMounted(async () => {
  pagingRef.value.complete([]);
  showLoading();
  const position = await Location.reverseGeocoderLocation();
  hideLoading();
  if (!position) return;
  const { address_component } = position;
  state.params = { ...state.params, provinceName: address_component.province, cityName: address_component.city, areaName: address_component.district };
  fetchObtainNewsTagList();
  pagingRef.value?.reload();
});

// 请求资讯列表
const fetchObtainNewsList = async (pageNo: number, regionalData?: IProvinceCityDistrict) => {
  if (regionalData && isObject(regionalData)) {
    state.params = { ...state.params, ...regionalData };
  }
  const [err, res] = await to(HomeRequest.ObtainNewsList({ ...state.params, pageNo, hasLoading: true }));
  if (err) {
    pagingRef.value.complete(false);
    return;
  }
  pagingRef.value.complete(res.data.list);
};

// 请求资讯标签列表
const fetchObtainNewsTagList = () => {
  HomeRequest.ObtainNewsTagList({ secondClassifyIds: btnInformation!.classifyIds }).then((res) => {
    state.tagList = res.data;
  });
};

// 搜索数据
const handleSearch = (libraryName: string) => {
  state.params = { ...state.params, libraryName };
  pagingRef.value.reload();
};

// 标签点击事件
const handleTagListClick = (tag: number) => {
  if (state.selectTag.find((item) => item === tag)) {
    state.selectTag = state.selectTag.filter((item) => item !== tag);
  } else {
    state.selectTag.push(tag);
  }
  state.params = { ...state.params, tagIds: state.selectTag.toString() };
  pagingRef.value.reload();
};

// 处理前往选择地区界面
const handleNavigateSelectAddressScreen = () => {
  HomeRequest.ObtainNationalUrbanAreaData({ hasLoading: true }).then((res) => {
    navigate({ url: `/subcontract/home/newsClassification/SelectAddressScreen?params=${state.params}&data=${encodeURIComponent(JSON.stringify(res.data))}` });
  });
};

defineExpose({
  fetchObtainNewsList,
});
</script>

<template>
  <view class="c-bg" :style="{ paddingTop: `${store.$state.menuInfo.top}px`, height: store.$state.menuInfo.height + 8 + 'px', paddingRight: store.$state.menuInfo.width + 12 + 'px' }">
    <view class="w-full flex items-center justify-between" :style="{ height: 'calc(100% - 8px)' }">
      <i class="i-mingcute:left-fill text-[28px]" @click="navigate({ type: 'navigateBack', url: '' })" />
      <view class="flex-1 ml-[8px] flex items-center" @click="handleNavigateSelectAddressScreen">
        <i class="i-icon-park-outline:local"></i>
        <text class="ml-4px">{{ state.params.areaName || state.params.cityName || state.params.provinceName || '选择地区' }}</text>
      </view>
    </view>
  </view>
  <view class="c-bg c-pd pt-0"><van-search shape="round" placeholder="请输入产品关键词" @search="handleSearch($event.detail)" /></view>
  <scroll-view scroll-x class="w-full c-pd whitespace-nowrap">
    <view class="py-4px px-8px c-br mr-12px inline-block" :class="state.selectTag.find((tag) => tag === item.id) ? 'c-bg-sec text-white' : 'bg-white'" v-for="item in state.tagList" :key="item.id" @click="handleTagListClick(item.id)">{{ item.name }}</view>
  </scroll-view>
  <view :style="{ height: `calc(100vh - ${store.$state.headerHeight + 46 + 52}px)` }">
    <z-paging ref="pagingRef" v-model="state.newList" :auto="false" @query="fetchObtainNewsList" empty-view-text="暂无数据" :auto-height="false" :fixed="false" safe-area-inset-bottom use-safe-area-placeholder>
      <view v-for="item in state.newList" :key="item.libraryId" class="w-50% c-pd pt-0 pr-0" @click="navigate({ url: `/subcontract/home/newsClassification/NewsDetails?id=${item.libraryId}` })">
        <view class="bg-white c-br overflow-hidden w-full">
          <image class="w-full h-100px" :src="item.mainImage" mode="aspectFill" />
          <view class="py-4px px-4px box-content min-h-60px flex flex-col justify-between">
            <text class="c-text-ellipsis-2 c-text-12">{{ item.libraryName }}</text>
            <view class="flex justify-between items-center c-text-12 c-text-color-grey mt-4px">
              <view class="flex items-center"><i class="i-mdi:eye mr-4px"></i> {{ item.viewNums }}</view>
              <view class="flex items-center"><i class="i-mingcute:thumb-up-2-fill mr-4px"></i>{{ item.upNums }}</view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>
<style scoped lang="scss">
:deep(.van-search) {
  padding: 0 !important;
  background: transparent !important;
}

:deep(.zp-paging-container-content) {
  display: flex;
  flex-wrap: wrap;
  padding-right: 12px;
}

:deep(.zp-l-container) {
  width: 100vw;
}
</style>
